package com.af.monitorModule.timmer;

import com.af.monitorModule.generator.entity.Company;
import com.af.monitorModule.generator.entity.ErrorSend;
import com.af.monitorModule.generator.entity.Monitor;
import com.af.monitorModule.generator.entity.SingleValue;
import com.af.monitorModule.generator.mapper.CompanyMapper;
import com.af.monitorModule.generator.mapper.ErrorSendMapper;
import com.af.monitorModule.generator.mapper.SingleValueMapper;
import com.af.monitorModule.generator.mapper.UtilMapper;
import com.af.monitorModule.generator.service.ErrorSendService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
public class CheckHeart {

    @Autowired
    private UtilMapper utilMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private SingleValueMapper singleValueMapper;

    @Autowired
    private ErrorSendService errorSendService;

    private static final Logger logger = LoggerFactory.getLogger(CheckHeart.class);


    @Scheduled(cron = "0 * * * * ? ")
    public void checkHeart(){
        List<Monitor> noHeart = utilMapper.findNoHeart();

        if (noHeart.size() > 0){
            StringBuilder look = new StringBuilder();
            look.append("## 监控掉线，3分钟以上未心跳的监控,共").append(noHeart.size()).append("个 \n\n");
            noHeart.forEach((monitor)->{
                Company company = companyMapper.selectById(monitor.getCompanyId());
                Duration duration = Duration.between(monitor.getHeartbeat(), LocalDateTime.now());
                look.append("--- ")
                    .append("\n - 所属公司：").append(company.getCompanyName())
                    .append("\n - 监控名称：").append(monitor.getMonitorName())
                    .append("\n - 最后心跳时间：").append(monitor.getHeartbeat().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .append("\n - 已经失联时间：").append(duration.toMinutes()).append("分钟 \n\n");
            });
            SingleValue singleValue = singleValueMapper.selectOne(new QueryWrapper<SingleValue>().eq("name", "监控钉钉"));
            logger.warn(look.toString() + "\n");
            String data = "{\"msgtype\":\"markdown\",\"markdown\":{\"title\":\"通知\",\"text\":\""+look.toString()+" \"},\"at\":{\"atMobiles\":[],\"isAtAll\":true}}";
            JSONObject send = JSON.parseObject(data);
            ResponseEntity<String> stringResponseEntity = new RestTemplate().postForEntity(singleValue.getValue(), send, String.class);
            if (stringResponseEntity.getStatusCodeValue() != 200){
                errorSendService.save(new ErrorSend()
                        .setSendCode(""+stringResponseEntity.getStatusCodeValue())
                        .setSendMonitorId(-1)
                        .setSendTime(LocalDateTime.now())
                        .setSendUrl(singleValue.getValue())
                        .setSendValue(send.toJSONString()));
            }
        }
    }
}
